package website.haicheng.core.exceptions;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import website.haicheng.core.base.Resp;
import website.haicheng.core.exceptions.auth.AuthException;
import website.haicheng.core.exceptions.system.SystemException;
import website.haicheng.core.exceptions.util.ConstraintNotMatchException;
import website.haicheng.core.exceptions.util.UtilException;

import java.util.List;

/**
 * @description:
 * @author: 582895699@qq.com
 * @time: 2021/2/12 下午 09:12
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 运行时异常统一处理
     *
     * @param e RuntimeException
     * @return Resp
     */
    @ExceptionHandler(value = RuntimeException.class)
    public Resp runtimeExceptionHandler(RuntimeException e) {
        e.printStackTrace();
        return Resp.error("系统异常，请稍后再试！");
    }

    /**
     * auth模块异常处理
     *
     * @param e AuthException
     * @return Resp
     */
    @ExceptionHandler(value = AuthException.class)
    public Resp authExceptionHandler(AuthException e) {
        return Resp.error(e.getMessage());
    }

    /**
     * system模块异常处理
     *
     * @param e SystemException
     * @return Resp
     */
    @ExceptionHandler(value = SystemException.class)
    public Resp systemExceptionHandler(SystemException e) {
        return Resp.error(e.getMessage());
    }

    /**
     * util工具类异常处理
     *
     * @param e SystemException
     * @return Resp
     */
    @ExceptionHandler(value = UtilException.class)
    public Resp utilExceptionHandler(UtilException e) {
        return Resp.error(e.getMessage());
    }


    /**
     * 判断条件异常处理
     *
     * @param e SystemException
     * @return Resp
     */
    @ExceptionHandler(value = ConstraintNotMatchException.class)
    public Resp constraintNotMatchExceptionHandler(ConstraintNotMatchException e) {
        return Resp.error(e.getMessage());
    }


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Resp methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        List<ObjectError> list = e.getBindingResult().getAllErrors();
        String message = list.get(0).getDefaultMessage();
        return Resp.error(message);

    }
}
